import React, { createRef, PureComponent } from 'react'
import { connect } from '@umijs/max'
import { Button, InputNumber, message, Modal, Popconfirm, Spin, Tabs, Upload } from 'antd'
import { ExclamationCircleOutlined } from '@ant-design/icons'
import { Dimension, DispatchConf, OperateRecord, Result, Source, ViewDetail } from './page-components'
import { CreateDiffEditor, DataDevLogger, ProTable, ProTableOptions } from '@/components'
import Tools from '@/utils/Tools'
import styles from './index.less'
import {
  checkGrammar,
  collectOnlineData,
  flinkLockNode,
  flinkPublish,
  getEnvDetail,
  getLog,
  getSqlTaskScrpit,
  getSqlTaskSourceTables,
  getTaskDetail,
  rollbackVersion,
  saveSqlTaskScript,
  startDebug,
  stopDebug
} from '../api'
import { SUAN_PAN } from '@/utils/https'

const Bus = Tools.Bus
const { TabPane } = Tabs

@connect(({ global }) => ({ themeValue:global.themeValue}))
export default class FlinkSql extends PureComponent {
  constructor(props) {
    super(props)
    this.state = {
      loggerList: [],
      scheduleStatus: 0,
      selectedBtn: null,
      recordModal: false,
      fetchingLoading: false,
      collectValue: 100,
      edit: false,
      runState: 0,
      script: '',
      selectedColumns: [],
      mappingTables: [],
      recordIndex: 0,
      rollbacking: false,
      historyTabs: [
        { name: '代码', component: null },
        { name: '环境参数', component: null },
      ],
      resultss: [
        {
          result: '运行日志',
          value: ['暂无运行'],
          key: 'logger',
          name: '运行日志',
        },
      ],
      activeKey: '0',
    }
    this.viewDetailRef = createRef()
    this.operateRecordRef = createRef()
    this.dispatchConfRef = createRef()
    this.dimensionRef = createRef()
    this.sourceRef = createRef()
    this.resultRef = createRef()
    this.eddiff = createRef()
    this.time = null
    this.editorRef = createRef()
  }

  componentDidMount() {
    this.getSqlTaskScrpit()
    this.getTaskDetail()
  }

  componentWillUnmount() {
  }

  getSqlTaskScrpit = () => {
    const { taskNode } = this.props
    getSqlTaskScrpit({ nodeId: taskNode.nodeId }).then((res) => {
      if (res.status === 200) {
        this.setState({
          script: res.data || '',
        })
      }
    })
  }

  saveSql = (val) => {
    const script = val || this.editorRef.current.getEditorValue()
    const { taskNode } = this.props
    saveSqlTaskScript({ nodeId: taskNode.nodeId, script }).then((res) => {
      if (res.status === 200) {
        this.setState({
          edit: false,
        })
        this.getTaskDetail()
        message.success(res.msg)
      } else {
        message.error(res.mag)
      }
    })
  }

  // eslint-disable-next-line react/no-unused-class-component-methods
  toggleViewDetail = () => {
    this.operateRecordRef && this.operateRecordRef?.current?.toggleOperateRecord(false)
    this.dispatchConfRef && this.dispatchConfRef?.current?.toggleDispatchConf(false)
    this.resultRef && this.resultRef?.current?.toggleResult(false)
    this.dimensionRef && this.dimensionRef?.current?.toggleDimension(false)
    this.sourceRef && this.sourceRef?.current?.toggleSource(false)
    this.viewDetailRef && this.viewDetailRef?.current?.toggleViewDetail()
    this.setState({
      selectedBtn: 'detail',
    })
  };

  toggleOperateRecord = () => {
    this.dispatchConfRef && this.dispatchConfRef?.current?.toggleDispatchConf(false)
    this.viewDetailRef && this.viewDetailRef?.current?.toggleViewDetail(false)
    this.resultRef && this.resultRef?.current?.toggleResult(false)
    this.dimensionRef && this.dimensionRef?.current?.toggleDimension(false)
    this.sourceRef && this.sourceRef?.current?.toggleSource(false)
    this.operateRecordRef && this.operateRecordRef?.current?.toggleOperateRecord()
    this.setState({
      selectedBtn: 'record',
    })
  }

  toggleDispatchConf = () => {
    this.viewDetailRef && this.viewDetailRef?.current?.toggleViewDetail(false)
    this.operateRecordRef && this.operateRecordRef?.current?.toggleOperateRecord(false)
    this.resultRef && this.resultRef?.current?.toggleResult(false)
    this.dimensionRef && this.dimensionRef?.current?.toggleDimension(false)
    this.sourceRef && this.sourceRef?.current?.toggleSource(false)
    this.dispatchConfRef && this.dispatchConfRef?.current?.toggleDispatchConf()
    this.setState({
      selectedBtn: 'conf',
    })
  }

  toggleSource = () => {
    this.viewDetailRef && this.viewDetailRef?.current?.toggleViewDetail(false)
    this.operateRecordRef && this.operateRecordRef?.current?.toggleOperateRecord(false)
    this.dispatchConfRef && this.dispatchConfRef?.current?.toggleDispatchConf(false)
    this.resultRef && this.resultRef?.current?.toggleResult(false)
    this.dimensionRef && this.dimensionRef?.current?.toggleDimension(false)
    this.sourceRef && this.sourceRef?.current?.toggleSource()
    this.setState({
      selectedBtn: 'source',
    })
  }

  toggleResult = () => {
    this.viewDetailRef && this.viewDetailRef?.current?.toggleViewDetail(false)
    this.operateRecordRef && this.operateRecordRef?.current?.toggleOperateRecord(false)
    this.dispatchConfRef && this.dispatchConfRef?.current?.toggleDispatchConf(false)
    this.dimensionRef && this.dimensionRef?.current?.toggleDimension(false)
    this.sourceRef && this.sourceRef?.current?.toggleSource(false)
    this.resultRef && this.resultRef?.current?.toggleResult()
    this.setState({
      selectedBtn: 'result',
    })
  }

  toggleDimension = () => {
    this.viewDetailRef && this.viewDetailRef?.current?.toggleViewDetail(false)
    this.operateRecordRef && this.operateRecordRef?.current?.toggleOperateRecord(false)
    this.dispatchConfRef && this.dispatchConfRef?.current?.toggleDispatchConf(false)
    this.sourceRef && this.sourceRef?.current?.toggleSource(false)
    this.resultRef && this.resultRef?.current?.toggleResult(false)
    this.dimensionRef && this.dimensionRef?.current?.toggleDimension()
    this.setState({
      selectedBtn: 'dimension',
    })
  }

  // 任务开始
  startDebug = () => {
    if (this.state.runState === 1) return
    const { taskNode } = this.props
    startDebug({
      nodeId: taskNode.nodeId,
    }).then((res) => {
      if (res.status === 200) {
        message.success(res.msg)
        this.setState({
          jobId: res.data.jobId,
          runState: 1,
          loggerList: [res.msg],
          testModal: false,
        })
        Bus.emit('iconUpFn', this.props.taskNode.nodeId)
        this.getLog(res.data.jobId)
      } else {
        message.error(res.msg)
      }
    })
  }

  // 任务日志
  getLog = (jobId, offset) => {
    getLog({
      jobId,
      offset: offset || offset === 0 ? offset : 0,
    }).then((res) => {
      if (res.status === 200) {
        clearTimeout(this.time)
        const { logContent, logEnd, results } = res.data
        const { resultss } = this.state

        let { loggerList } = this.state
        if (logContent && logContent.length) {
          loggerList = loggerList.concat(logContent)
        }
        resultss[0].value = loggerList || []

        const arr = this.state.resultss
        let newResults = results ? [...results] : []

        if (newResults && newResults.length) {
          newResults.map((obj) => {
            obj.jobId = jobId
          })
          newResults = arr.concat(newResults)
        }

        newResults && newResults.length
          ? newResults.map((item, k) => {
            item.name ? null : (item.name = `结果[${k}]`)
          })
          : null
        this.setState({
          loggerList,
          resultss: newResults && newResults.length ? newResults : arr,
        }, () => {
          this.time = setTimeout(() => {
            this.getLog(jobId, res.data.offset)
          }, 2000)
        })
        if (logEnd) {
          clearTimeout(this.time)
          this.setState({
            runState: 0,
          })
        }
      } else {
        clearTimeout(this.time)
        this.setState({
          runState: 0,
        })
        message.error(res.msg)
      }
    })
  }

  // 结束任务
  stopDebug = () => {
    if (this.state.runState === 0) return
    const { jobId } = this.state
    stopDebug({ jobId }).then((res) => {
      if (res.status === 200) {
        message.success(res.msg)
        clearTimeout(this.time)
        this.setState({
          runState: 0,
        })
      } else {
        message.error(res.msg)
      }
      this.flowTaskStatus(jobId)
    })
  }

  activeKeyonChange = (activeKey) => {
    this.setState({ activeKey })
  };

  setEditorState = (script) => {
    if (script !== this.state.script) {
      this.setState({ edit: true })
    }
  }

  /**
   * 切换历史版本tab
   */
  changeHsitoryTab = (index) => {
    console.log(index)
    this.setState(
      {
        recordIndex: index,
      },
      () => {
        if (index === 0) {
          this.showHistoryDiffEditor(
            this.editorRef.current.getEditorValue(),
            this.state.scriptRes,
          )
        } else {
          this.showHistoryDiffEditor(this.state.envCurrent, this.state.envOld)
        }
      },
    )
  }

  showHistoryDiffEditor = (nowData, oldData) => {
    clearInterval(this.historyInterval)
    this.historyInterval = setTimeout(() => {
      this.eddiff.innerHTML = ''
      const now = window.monaco.editor.createModel(nowData, 'sql')
      const origin = window.monaco.editor.createModel(oldData, 'sql')
      const diffEditor = window.monaco.editor.createDiffEditor(this.eddiff, {
        enableSplitViewResizing: true,
        readOnly: true,
      })
      diffEditor.setModel({
        original: now,
        modified: origin,
      })
    }, 10)
  }

  /**
   * 查看版本对比
   */
  showRecord = (record) => {
    const { taskNode } = this.props
    let scriptRes = ''
    let envOld = ''
    let envCurrent = ''
    getSqlTaskScrpit({ nodeId: taskNode.nodeId, versionId: record.id }).then((res) => {
      if (res.status === 200) {
        scriptRes = res.data || ''
      }
      getEnvDetail({ nodeId: taskNode.nodeId, versionId: record.id }).then((res1) => {
        if (res1.status === 200) {
          envOld = res1.data || ''
        }
        getEnvDetail({ nodeId: taskNode.nodeId }).then((res2) => {
          if (res2.status === 200) {
            envCurrent = res2.data || ''
          }
          this.setState(
            {
              recordModal: true,
              scriptRes,
              envOld,
              envCurrent,
              recordId: record.id,
            },
            () => {
              this.changeHsitoryTab(0)
            },
          )
        })
      })
    })
  }

  /**
   * 版本回滚
   */
  rollbackVersion = () => {
    const { taskNode } = this.props
    Modal.confirm({
      title: '确认执行任务回滚版本吗？',
      content: '任务回滚可帮助您恢复历史版本的任务数据！',
      onOk: () => {
        rollbackVersion({
          nodeId: taskNode.nodeId,
          versionId: this.state.recordId,
        }).then((res) => {
          if (res.status === 200) {
            message.success(res.msg)
            this.setState(
              {
                recordModal: false,
                rollbacking: true,
              },
              () => {
                this.setState({
                  rollbacking: false,
                })

                this.getTaskDetail()
                this.getSqlTaskScrpit()
              },
            )
          } else {
            message.error(res.msg)
          }
        })
      },
    })
  }

  /**
   * 语法检测
   */
  realTimeDevCheckGrammar = async () => {
    const { taskNode } = this.props
    checkGrammar({ sql: this.editorRef.current.getEditorValue() }).then((res) => {
      if (res.status === 200) {
        message.success(res.msg)
        this.editorRef.current.setModelMarkersOwner(res.data, taskNode.key * 2)
      } else {
        message.error(res.msg)
      }
    })
  };

  // 发布and取消发布
  flinkPublish = (isPublished) => {
    const { taskNode } = this.props
    this.setState({
      lodings: true,
    })
    flinkPublish({ id: taskNode.nodeId, isPublished }).then((res) => {
      if (res.status === 200) {
        this.getTaskDetail()
        message.success(res.msg)
      } else {
        message.error(res.msg)
      }
      this.setState({
        lodings: false,
      })
    })
  }

  // 任务详情
  getTaskDetail = () => {
    const { taskNode } = this.props
    const { nodeId } = taskNode || {}
    const params = {
      nodeId,
    }
    getTaskDetail(params).then((res) => {
      if (res.status === 200) {
        this.setState({
          taskDetail: res.data || '',
          scheduleStatus: res.data.isPublished || 0,
          isLocked: res.data.isLocked,
        })
      }
    })
  }

  // 锁定解锁
  flinkLockNode = (isLocked) => {
    const { taskNode } = this.props
    const { nodeId } = taskNode || {}
    flinkLockNode({ id: nodeId, isLocked }).then((res) => {
      if (res.status === 200) {
        message.success(res.msg)
        this.setState({
          isLocked,
        })
      } else {
        message.error(res.msg)
      }
    })
  }

  confirm = () => {
    Modal.confirm({
      title: '提交',
      icon: <ExclamationCircleOutlined />,
      content: '文件被修改，是否要保存？',
      okText: '确认',
      cancelText: '取消',
      onOk: () => {
        this.saveSql()
      },
    })
  };

  /**
   * 上传数据集
   */
  fileChange = (info) => {
    this.setState({
      loading: true,
    })
    if (info.file.status === 'done') {
      const { tableDataHash, selectedMappingTable } = this.state
      tableDataHash[selectedMappingTable] = info.file.response.data
      this.setState({
        tableDataHash: { ...tableDataHash },
        loading: false,
      })
      if (info.file.response.status == 1) {
        message.success('上传成功')
      } else {
        message.warning(info.file.response.msg || '上传失败')
      }
    } else if (info.file.status === 'error') {
      this.setState({
        loading: false,
      })
      message.warning('上传失败')
    }
  };

  /**
   * 下载模板
   */
  downloadTemplate = () => {
    if (!this.state.selectedMappingTable) {
      message.error('请先选择数据表')
      return
    }
    window.location.href = `${SUAN_PAN}/api/v1/flink/sql/downloadSqlTaskTemplate?nodeId=${this.props.taskNode.nodeId}&tableName=${this.state.selectedMappingTable}`
  }

  /**
   * 获取映射表
   */
  getSqlTaskSourceTables = () => {
    this.setState({
      tableDataHash: {},
      testModal: true,
      fetchingLoading: true,
    })
    const { taskNode } = this.props
    const { nodeId } = taskNode || {}
    getSqlTaskSourceTables({ nodeId }).then((res) => {
      if (res.status === 200) {
        if (res.data.length <= 0) {
          message.warning('请先配置数据表')
          return
        }
        this.setState({
          mappingTables: res.data || [],
          selectedMappingTable: res.data[0].tableName,
          selectedColumns: res.data[0].fieldNames,
        })
      }
      this.setState({
        fetchingLoading: false,
      })
    })
  }

  /**
   * 采集线上数据
   * @returns
   */
  collectOnlineData = () => {
    this.setState({
      fetchingLoading: true,
    })
    const { selectedMappingTable, collectValue } = this.state
    const { taskNode } = this.props
    const { nodeId } = taskNode || {}
    collectOnlineData({
      maxCount: collectValue,
      nodeId,
      tableName: selectedMappingTable,
    }).then((res) => {
      if (res.status === 200) {
        const { tableDataHash } = this.state
        tableDataHash[selectedMappingTable] = res.data || []
        this.setState({
          tableDataHash: { ...tableDataHash },
        })
        message.success(res.msg)
      } else {
        message.warning(res.msg)
      }
      this.setState({
        fetchingLoading: false,
      })
    })
  }

  /**
   * 执行调试
   */
  showTest = () => {
    if (this.state.jobId) {
      message.error('已有任务正在运行')
      return
    }
    this.getSqlTaskSourceTables()
  }

  render() {
    const { taskNode } = this.props
    const {
      selectedBtn, resultss, loggerList, runState, script, recordModal, historyTabs,
      recordIndex, taskDetail, edit, testModal, fetchingLoading, collectValue,
      selectedMappingTable, selectedColumns, mappingTables, rollbacking, isLocked,
    } = this.state
    return (
      rollbacking ? null : (
        <div className={styles.flinkSql_container}>
          <div className={styles.flinkSql_panel_header}>
            <dl onClick={() => {
              this.saveSql()
            }}
            >
              <dt><i className="iconfont_new iconbaocun" /></dt>
              <dd>保存</dd>
            </dl>
            {runState != 1 ? (
              <dl
                onClick={() => {
                  if (edit) {
                    this.confirm()
                  } else {
                    this.showTest()
                  }
                }}
                className={`${runState == 1 && styles.disable}`}
              >
                <dt><i className="iconfont icon-yunhang" /></dt>
                <dd>调试</dd>
              </dl>
            ) : (
              <dl
                className="task-collect-operation-dl"
                onClick={() => {
                  this.stopDebug()
                }}
              >
                <dt>
                  <i className="iconfont_new icontingzhi" />
                </dt>
                <dd>停止调试</dd>
              </dl>
            )}

            {isLocked ? (
              <dl onClick={() => {
                this.flinkLockNode(0)
              }}
              >
                <dt><i className="iconfont_new iconsuo" /></dt>
                <dd>解锁</dd>
              </dl>
            ) : (
              <dl onClick={() => {
                this.flinkLockNode(1)
              }}
              >
                <dt><i className="iconfont_new iconsuo" /></dt>
                <dd>锁定</dd>
              </dl>
            )}
            <dl onClick={() => {
              this.realTimeDevCheckGrammar()
            }}
            >
              <dt><i className="iconfont_new icondaimajiancha" /></dt>
              <dd>代码检查</dd>
            </dl>
            <span className={styles.flinkSql_panel_button} style={{ float: 'right' }}>
              {this.state.scheduleStatus == 0 ? (
                <Button
                  loading={this.state.lodings}
                  onClick={() => {
                    if (edit) {
                      this.confirm()
                    } else {
                      this.flinkPublish(1)
                    }
                  }}
                >发布
                </Button>
              ) : (
                <Button
                  loading={this.state.lodings}
                  onClick={() => {
                    this.flinkPublish(0)
                  }}
                >取消发布
                </Button>
              )}
              <Button
                type="primary"
                style={{ marginLeft: '.16rem' }}
                onClick={() => {
                  window.location = `${window.suanpan}#/data-development/realTime/task-operation`
                }}
              >运维
              </Button>
            </span>
          </div>
          <div className={styles.flinkSql_editor}>
            <div className={styles.flinkSql_editor_box}>
              <div className={styles.flinkSql_editor_left}>
                <CreateDiffEditor
                  theme={this.props?.themeValue==='light'?"vs":"vs-dark"}
                  ref={this.editorRef}
                  language="flink"
                  restData={script}
                  realTimeSave={(val) => {
                    this.setEditorState(val)
                  }}
                  onSave={(val) => {
                    this.saveSql(val)
                  }}
                  editorId={`real-time-task-editor${taskNode && taskNode.nodeId}`}
                />
              </div>
              <div className={styles.flinkSql_right}>
                <span className={`${styles.flinkSql_right_span} ${selectedBtn === 'detail' ? styles.on : ''}`} onClick={this.toggleViewDetail}>任务详情</span>
                <span className={`${styles.flinkSql_right_span} ${selectedBtn === 'source' ? styles.on : ''}`} onClick={this.toggleSource}>源表</span>
                <span className={`${styles.flinkSql_right_span} ${selectedBtn === 'result' ? styles.on : ''}`} onClick={this.toggleResult}>结果表</span>
                <span className={`${styles.flinkSql_right_span} ${selectedBtn === 'dimension' ? styles.on : ''}`} onClick={this.toggleDimension}>维度表</span>
                <span className={`${styles.flinkSql_right_span} ${selectedBtn === 'record' ? styles.on : ''}`} onClick={this.toggleOperateRecord}>环境参数</span>
                <span className={`${styles.flinkSql_right_span} ${selectedBtn === 'conf' ? styles.on : ''}`} onClick={this.toggleDispatchConf}>调度配置</span>
                <ViewDetail ref={this.viewDetailRef} taskDetail={taskDetail} getTaskDetail={this.getTaskDetail} />
                <DispatchConf ref={this.dispatchConfRef} taskNode={taskNode} detailTaskFlow={this.detailTaskFlow} />
                <OperateRecord ref={this.operateRecordRef} taskNode={taskNode} />
                <Result getTaskDetail={this.getTaskDetail} ref={this.resultRef} taskNode={taskNode} />
                <Dimension getTaskDetail={this.getTaskDetail} ref={this.dimensionRef} taskNode={taskNode} />
                <Source getTaskDetail={this.getTaskDetail} ref={this.sourceRef} taskNode={taskNode} />
              </div>
            </div>
            {isLocked ? <div className={styles.flinkSql_isLocked} /> : null}
          </div>
          <DataDevLogger
            list={loggerList || []}
            results={resultss}
            jobId={this.state.jobId}
            className={styles.flow_log}
            style="flow"
            activeKey={this.state.activeKey}
            activeKeyonChange={this.activeKeyonChange}
            taskId={taskNode.nodeId}
            center={
              <TabPane
                forceRender={false}
                tab="历史版本"
                key="tabel"
                closable={false}
              >
                <ProTable
                  columns={[
                    {
                      title: '发布时间',
                      dataIndex: 'publishTime',
                      width: '25%',
                      key: 'publishTime',
                      filterSearch: true,
                    },
                    {
                      title: '发布人',
                      dataIndex: 'username',
                      width: '20%',
                      key: 'username',
                    },
                    {
                      title: '描述',
                      dataIndex: 'remark',
                      width: '30%',
                      key: 'remark',
                    },
                    {
                      title: '操作',
                      dataIndex: 'operation',
                      width: '25%',
                      key: 'operation',
                      render: (text, record, index) => (
                        <ProTableOptions>
                          <span
                            key="check"
                            onClick={() => {
                              this.showRecord(record)
                            }}
                          >
                            版本对比
                          </span>
                        </ProTableOptions>
                      ),
                    },
                  ]}
                  url="/api/v1/flink/sql/getSqlTaskVersion"
                  query={{
                    id: taskNode.nodeId,
                  }}
                />
              </TabPane>
            }
          />
          <Modal
            destroyOnClose
            title="版本对比"
            visible={recordModal}
            okText="版本回滚"
            width={1000}
            className=""
            onOk={() => {
              this.rollbackVersion()
            }}
            onCancel={() => {
              this.setState({
                recordModal: false,
              })
            }}
          >
            <div className={styles.real_time_props_top_tabs}>
              {historyTabs.map((item, index) => (
                <div
                  key={index}
                  className={`${styles.real_time_props_top_tab} ${recordIndex == index ? styles.active : ''}`}
                  onClick={() => {
                    this.changeHsitoryTab(index)
                  }}
                >
                  {item.name}
                </div>
              ))}
              <div className={styles.real_time_props_top_flex} />
            </div>
            <div className={styles.real_time_diff_history}>
              <span>当前版本</span>
              <span>历史版本</span>
            </div>
            <div
              ref={(div) => {
                this.eddiff = div
              }}
              className={styles.real_time_diff_editor}
            />
          </Modal>

          <Modal
            destroyOnClose
            title="调试"
            visible={testModal}
            cancelText="取消"
            okText="调试"
            width={1000}
            className="real-time-test"
            onOk={() => {
              this.startDebug()
            }}
            onCancel={() => {
              this.setState({
                testModal: false,
              })
            }}
          >
            <Spin spinning={fetchingLoading}>
              <div className={styles.real_time_test_title}>
                代码调试用于校验业务逻辑或语法的正确性：
                <br />
                1、上传自定义数据、模拟作业运行、检查输出结果，最终验证业务逻辑的正确性，仅需上传源表数据，维表直接读取配置，无需上传
                <br />
                2、线上数据采集时长为30秒，若超过1分钟数据仍未采集至指定条数，则采集停止
              </div>
              <div className={styles.real_time_test_body}>
                <div className={styles.real_time_test_tables}>
                  <div className={styles.real_time_test_table_name}>数据表</div>
                  {mappingTables.map((item) => (
                    <div
                      title={item.tableName}
                      onClick={() => {
                        this.setState({
                          selectedMappingTable: item.tableName,
                          selectedColumns: item.fieldNames,
                        })
                      }}
                      key={item.tableName}
                      className={`${styles.real_time_test_table} ${selectedMappingTable == item.tableName ? styles.active : ''}`}
                    >
                      {item.tableName}
                    </div>
                  ))}
                </div>
                <div className={styles.real_time_test_datas}>
                  <div className={styles.real_time_test_hint}>数据上传</div>
                  <div className={styles.real_time_test_upload}>
                    <span
                      onClick={() => {
                        this.downloadTemplate()
                      }}
                    >
                      下载模板
                    </span>
                    <div>
                      <Upload
                        action={`${SUAN_PAN}/api/v1/flink/sql/uploadDebugData`}
                        accept=".csv"
                        showUploadList={false}
                        disabled={!selectedMappingTable}
                        data={{
                          nodeId: taskNode.nodeId,
                          tableName: this.state.selectedMappingTable,
                        }}
                        onChange={(info) => {
                          this.fileChange(info)
                        }}
                        headers={{
                          'X-Project-Id': sessionStorage.getItem('projectId'),
                        }}
                      >
                        <Button
                          loading={this.state.loading}
                          disabled={!selectedMappingTable}
                        >
                          上传文件
                        </Button>
                      </Upload>
                    </div>
                    <div className={styles.real_time_test_title}>
                      文件支持扩展名 .csv，条数应小于1000条且不超过1MB;
                      文件仅支持UTF-8格式;
                    </div>
                  </div>

                  <div className={styles.real_time_test_hint}>
                    数据预览
                    <Popconfirm
                      icon={null}
                      onConfirm={() => {
                        this.collectOnlineData()
                      }}
                      title={
                        <div>
                          采集条数:{' '}
                          <InputNumber
                            style={{ marginLeft: '20px' }}
                            min={1}
                            max={1000}
                            defaultValue={100}
                            value={collectValue}
                            onChange={(value) => {
                              this.setState({
                                collectValue: value,
                              })
                            }}
                          />
                        </div>
                      }
                    >
                      <span className={styles.real_time_test_right}>采集线上数据</span>
                    </Popconfirm>
                  </div>
                  <div className={styles.real_time_test_preview}>
                    <ProTable
                      dataSource={
                        this.state.tableDataHash && this.state.tableDataHash[this.state.selectedMappingTable] || []
                      }
                      columns={selectedColumns.map((field, index) => ({
                        title: field,
                        dataIndex: index,
                        key: index,
                        width: '10%',
                      }))}
                    />
                  </div>
                </div>
              </div>
            </Spin>
          </Modal>
        </div>
      )
    )
  }
}
